package cn.zqh.auth.service;

import cn.hutool.core.collection.CollUtil;
import cn.zqh.auth.constant.RedisConstant;
import cn.zqh.auth.mapper.RouterMapper;
import cn.zqh.auth.pojo.Router;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 资源与角色匹配关系管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
public class ResourceServiceImpl {

    private Map<String, List<String>> resourceRolesMap;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private RouterMapper routerMapper;

    @PostConstruct
    public void initData() {
        resourceRolesMap = new TreeMap<>();
        List<Router> routers = routerMapper.selectList(null);

        for (Router router : routers) {
            ArrayList<String> list = CollUtil.toList();
            String[] split = router.getRouterPermission().split(",");
            if (split.length > 1){
                for (String s : split) {
                    list.add(s);
                }
            }else {
                list.add(split[0]);
            }
            System.out.println(list);
            resourceRolesMap.put(router.getRouterName(),list);
        }
        //原本写死了的
//        resourceRolesMap.put("/api/hello", CollUtil.toList("ADMIN"));
//        resourceRolesMap.put("/api/user/currentUser", CollUtil.toList("ADMIN", "TEST"));
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP, resourceRolesMap);
    }
}
